import random
import string
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
#鉴权
from django.core.cache import cache
from django.core.signing import Signer
from datetime import timedelta
from .models import customers,orders
#分页
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
# Create your views here.


#产生token
def createtoken(name):
    randomstr=''.join(random.choices(string.ascii_letters,k=8))
    token=Signer().sign(randomstr+name)
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
    return token
#校验token
def checktoken(request):
    reqtoken=request.META.get('HTTP_TOKEN')
    if reqtoken is None:
        return False,'xxxx'
    untoken=Signer().unsign(reqtoken)
    name=untoken[8:]
    cachetoken=cache.get(f'test_{name}')
    if cachetoken is None:
        return False,'xxxx'
    return True

#登录
@api_view(['POST'])
def login(request):
    data=JSONParser().parse(request)
    email=data.get('email')
    password=data.get('password')
    obj=customers.objects.get(email=email)
    if obj.password==password:
        token=createtoken(email)
        return JsonResponse({
            'code':200,
            'msg':'登录成功',
            'token':token
        })